package ${pPackage}.common.utils;

import ${pPackage}.pojo.Permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成菜单树
 */
public class MenuUtils {
    public static Map<String, Object> buildTree(List<Permission> permissions, Integer type) {
        Map<String, Object> map = new HashMap<>();
        List<Permission> finalNode = new ArrayList<>();
        List<String> points = new ArrayList<>();
        List<String> apis = new ArrayList<>();
        for (Permission menu : permissions) {
            switch (menu.getType()) {
                case Constants.PERMISSION_POINT: // 抽取按钮权限
                    points.add(menu.getCode());
                    break;
                case Constants.PERMISSION_API: // 抽取API权限
                    apis.add(menu.getCode());
                    break;
            }
            String topId = "0";
            if (topId.equals(menu.getPid())) {
                finalNode.add(selectTree(menu, permissions, map, type));
            }
        }
        map.put("points", points);
        map.put("apis", apis);
        map.put("menu", finalNode);
        return map;
    }

    private static Permission selectTree(Permission menu, List<Permission> menuList, Map<String, Object> map, Integer type) {
        menu.setChildren(new ArrayList<>());
        // 去除多余字段
        switch (menu.getType()) {
            case Constants.PERMISSION_MENU:
                menu.setPermissionApi(null);
                menu.setPermissionPoint(null);
                break;
            case Constants.PERMISSION_POINT:
                menu.setPermissionApi(null);
                menu.setPermissionMenu(null);
                break;
            case Constants.PERMISSION_API:
                menu.setPermissionMenu(null);
                menu.setPermissionPoint(null);
                break;
        }

        for (Permission menuItem : menuList) {
            if (menu.getId().equals(menuItem.getPid())) {
                if (menu.getChildren() == null) {
                    menu.setChildren(new ArrayList<>());
                }
                /**
                 * type 0 菜单不包含子按钮、子接口
                 */
                if (type == 0) {
                    // 处理菜单
                    if (Constants.PERMISSION_MENU == menuItem.getType()) {
                        menu.getChildren().add(selectTree(menuItem, menuList, map, type));
                    }
                } else {
                    menu.getChildren().add(selectTree(menuItem, menuList, map, type));
                }

            }
        }
        return menu;
    }
}
